<template>
  <div class="ssh-audit-container">

    <!-- 星空背景 -->
    <div class="starry-background">
      <div class="stars"></div>
      <div class="stars2"></div>
      <div class="stars3"></div>
    </div>

    <!-- 主要内容区域 -->
    <div class="audit-content">
      <!-- 页面标题 -->
      <div class="page-header glass-effect">
        <div class="header-content">
          <div class="title-section">
            <h1 class="page-title">
              <i class="fa fa-terminal"></i>
              SSH日志审计
            </h1>
            <p class="page-subtitle">监控SSH连接会话和命令执行记录</p>
          </div>
          <div class="stats-section">
            <div class="stat-card glass-effect">
              <div class="stat-number">{{ statistics.total_sessions || 0 }}</div>
              <div class="stat-label">总会话数</div>
            </div>
            <div class="stat-card glass-effect">
              <div class="stat-number">{{ statistics.active_sessions || 0 }}</div>
              <div class="stat-label">活跃会话</div>
            </div>
            <div class="stat-card glass-effect">
              <div class="stat-number">{{ statistics.total_commands || 0 }}</div>
              <div class="stat-label">执行命令</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 功能选项卡 -->
      <div class="tabs-section glass-effect">
        <el-tabs v-model="activeTab" class="audit-tabs">
          <el-tab-pane label="SSH会话记录" name="sessions">
            <div class="table-container">
              <el-table :data="sessions" style="width: 100%" v-loading="loading" class="audit-table">
                <el-table-column prop="session_id" label="会话ID" width="120">
                  <template #default="scope">
                    <span class="session-id">{{ scope.row.session_id?.substring(0, 8) + '...' || '-' }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="user_name" label="用户" min-width="100" />
                <el-table-column prop="host_name" label="主机" min-width="120" />
                <el-table-column prop="host_ip" label="IP地址" min-width="120" />
                <el-table-column prop="start_time" label="开始时间" min-width="160">
                  <template #default="scope">
                    <span class="time-text">{{ formatTime(scope.row.start_time) }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="status" label="状态" width="100">
                  <template #default="scope">
                    <el-tag :type="getStatusType(scope.row.status)" size="small" class="status-tag">
                      {{ scope.row.status }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="240">
                  <template #default="scope">
                    <div class="action-buttons">
                      <el-button @click="viewCommands(scope.row)" class="glass-action-btn">
                        <i class="fa fa-list"></i>
                        <span>查看命令</span>
                      </el-button>
                      <el-button @click="replaySession(scope.row)" class="glass-action-btn replay-btn">
                        <i class="fa fa-play"></i>
                        <span>回放</span>
                      </el-button>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-tab-pane>

          <el-tab-pane label="连接记录" name="connections">
            <div class="table-container">
              <el-table :data="connections" style="width: 100%" v-loading="loading" class="audit-table">
                <el-table-column prop="id" label="ID" width="60" />
                <el-table-column label="用户" min-width="100">
                  <template #default="scope">
                    <span>{{ scope.row.user?.username || scope.row.user_name || '-' }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="主机" min-width="120">
                  <template #default="scope">
                    <span>{{ scope.row.host?.hostname || scope.row.host_name || '-' }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="连接时间" min-width="160">
                  <template #default="scope">
                    <span class="time-text">{{ formatTime(scope.row.connected_at) }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="状态" width="100">
                  <template #default="scope">
                    <el-tag :type="scope.row.is_active ? 'success' : 'info'" size="small" class="status-tag">
                      {{ scope.row.is_active ? '活跃' : '已断开' }}
                    </el-tag>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>


    </div>
  </div>
</template>

<script setup lang="ts">
import { formatTime } from '@/utils/format'
import axios from 'axios'
import { onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()

const activeTab = ref('sessions')
const loading = ref(false)
const sessions = ref([])
const connections = ref([])

// 统计数据
const statistics = ref({
  total_sessions: 0,
  active_sessions: 0,
  total_commands: 0
})

const getStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    'active': 'success',
    'closed': 'info',
    'timeout': 'warning',
    'error': 'danger'
  }
  return statusMap[status] || 'info'
}

const viewCommands = (session: any) => {
  router.push(`/audit/commands?session_id=${session.session_id}`)
}

const replaySession = (session: any) => {
  if (session.session_id) {
    router.push(`/audit/replay/${session.session_id}`)
  }
}



const fetchSessions = async () => {
  loading.value = true
  try {
    // 使用正确的API端点获取SSH会话数据
    const response = await axios.get('/api/audit/sessions/')
    const data = response.data

    if (data.results) {
      sessions.value = data.results
    } else if (Array.isArray(data)) {
      sessions.value = data
    } else {
      sessions.value = []
    }

    // 更新统计数据
    statistics.value.total_sessions = sessions.value.length
    statistics.value.active_sessions = sessions.value.filter(s => s.status === 'active').length

    // 计算总命令数
    const totalCommands = sessions.value.reduce((sum, session) => {
      return sum + (session.command_count || 0)
    }, 0)
    statistics.value.total_commands = totalCommands

    console.log('SSH会话数据加载完成:', {
      total: sessions.value.length,
      active: statistics.value.active_sessions,
      commands: statistics.value.total_commands
    })

  } catch (error) {
    console.error('获取SSH会话失败:', error)
    // 如果API不存在，显示提示信息
    if (error.response?.status === 404) {
      console.warn('SSH审计API未实现，显示空数据')
      sessions.value = []
    }
  } finally {
    loading.value = false
  }
}

const fetchConnections = async () => {
  loading.value = true
  try {
    // 使用正确的API端点获取连接记录
    const response = await axios.get('/api/connections/')
    const data = response.data

    if (data.results) {
      connections.value = data.results
    } else if (Array.isArray(data)) {
      connections.value = data
    } else {
      connections.value = []
    }

    console.log('连接记录数据加载完成:', connections.value.length)

  } catch (error) {
    console.error('获取连接记录失败:', error)
    // 如果API不存在，显示提示信息
    if (error.response?.status === 404) {
      console.warn('连接记录API未实现，显示空数据')
      connections.value = []
    }
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchSessions()
  fetchConnections()
})
</script>

<style lang="scss" scoped>
/* 主容器 */
.ssh-audit-container {
  position: relative;
  min-height: 100vh;
  background: linear-gradient(135deg,
    rgba(0, 0, 0, 0.9) 0%,
    rgba(20, 20, 40, 0.95) 50%,
    rgba(0, 0, 0, 0.9) 100%
  );
  overflow-x: hidden;
}

/* 星空背景 */
.starry-background {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 0;
  pointer-events: none;
}

.stars, .stars2, .stars3 {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: transparent;
}

.stars {
  background-image:
    radial-gradient(2px 2px at 20px 30px, #eee, transparent),
    radial-gradient(2px 2px at 40px 70px, rgba(255,255,255,0.8), transparent),
    radial-gradient(1px 1px at 90px 40px, #fff, transparent);
  background-repeat: repeat;
  background-size: 200px 100px;
  animation: zoom 20s infinite linear;
}

.stars2 {
  background-image:
    radial-gradient(1px 1px at 40px 60px, #fff, transparent),
    radial-gradient(1px 1px at 120px 10px, rgba(255,255,255,0.7), transparent);
  background-repeat: repeat;
  background-size: 300px 200px;
  animation: zoom 40s infinite linear;
}

.stars3 {
  background-image:
    radial-gradient(1px 1px at 10px 10px, rgba(255,255,255,0.5), transparent);
  background-repeat: repeat;
  background-size: 400px 300px;
  animation: zoom 60s infinite linear;
}

@keyframes zoom {
  from { transform: scale(1); }
  to { transform: scale(1.5); }
}

/* 主要内容区域 */
.audit-content {
  position: relative;
  z-index: 10;
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

/* 玻璃效果基础样式 */
.glass-effect {
  background: rgba(164, 244, 186, 0.1);
  border: 1px solid rgba(164, 244, 186, 0.2);
  border-radius: 12px;
  backdrop-filter: blur(20px);
  box-shadow:
    0 8px 32px rgba(0, 0, 0, 0.3),
    inset 0 1px 0 rgba(255, 255, 255, 0.1);
}

/* 页面标题区域 */
.page-header {
  margin-bottom: 30px;
  padding: 30px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 30px;
}

.title-section {
  flex: 1;
}

.page-title {
  color: #00eaff;
  font-size: 2.5em;
  margin: 0 0 10px 0;
  text-shadow: 0 0 20px rgba(0, 234, 255, 0.5);
  display: flex;
  align-items: center;
  gap: 15px;

  i {
    font-size: 0.8em;
  }
}

.page-subtitle {
  color: rgba(255, 255, 255, 0.7);
  font-size: 1.1em;
  margin: 0;
}

.stats-section {
  display: flex;
  gap: 20px;
}

.stat-card {
  padding: 20px;
  text-align: center;
  min-width: 120px;

  .stat-number {
    color: #00eaff;
    font-size: 2em;
    font-weight: bold;
    text-shadow: 0 0 10px rgba(0, 234, 255, 0.3);
  }

  .stat-label {
    color: rgba(255, 255, 255, 0.8);
    font-size: 0.9em;
    margin-top: 5px;
  }
}

/* 选项卡区域 */
.tabs-section {
  margin-bottom: 30px;
  padding: 30px;
}

.audit-tabs {
  :deep(.el-tabs__header) {
    background: transparent;
    border-bottom: 1px solid rgba(164, 244, 186, 0.3);
  }

  :deep(.el-tabs__nav-wrap) {
    background: transparent;
  }

  :deep(.el-tabs__item) {
    color: rgba(255, 255, 255, 0.7);
    background: transparent;
    border: none;
    font-size: 1.1em;
    padding: 0 20px;
    height: 50px;
    line-height: 50px;
  }

  :deep(.el-tabs__item.is-active) {
    color: #00eaff;
    text-shadow: 0 0 10px rgba(0, 234, 255, 0.3);
  }

  :deep(.el-tabs__active-bar) {
    background: #00eaff;
    box-shadow: 0 0 10px rgba(0, 234, 255, 0.5);
  }

  :deep(.el-tabs__content) {
    background: transparent !important;
  }
}

.table-container {
  margin-top: 20px;
}

.audit-table {
  background: transparent !important;

  :deep(.el-table__header) {
    background: rgba(164, 244, 186, 0.1);
  }

  :deep(.el-table__header th) {
    background: transparent;
    color: #00eaff;
    border-bottom: 1px solid rgba(164, 244, 186, 0.3);
    font-weight: bold;
  }

  :deep(.el-table__body tr) {
    background: transparent;
  }

  :deep(.el-table__body td) {
    background: transparent;
    color: rgba(255, 255, 255, 0.8);
    border-bottom: 1px solid rgba(164, 244, 186, 0.1);
  }

  :deep(.el-table__body tr:hover td) {
    background: rgba(164, 244, 186, 0.05) !important;
  }
}

.session-id {
  font-family: monospace;
  color: #a4f4ba;
}

.time-text {
  color: rgba(255, 255, 255, 0.7);
  font-size: 0.9em;
}

.status-tag {
  font-weight: bold;
}

.action-buttons {
  display: flex;
  gap: 8px;
  flex-wrap: nowrap;
}

.glass-action-btn {
  background: rgba(164, 244, 186, 0.1) !important;
  border: 1px solid rgba(164, 244, 186, 0.3) !important;
  color: rgba(255, 255, 255, 0.9) !important;
  backdrop-filter: blur(10px) !important;
  border-radius: 6px !important;
  padding: 8px 12px !important;
  font-size: 12px !important;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1) !important;
  display: flex !important;
  align-items: center !important;
  gap: 4px !important;
  min-width: 80px !important;
  justify-content: center !important;
  box-shadow:
    0 2px 8px rgba(0, 0, 0, 0.1),
    inset 0 1px 0 rgba(255, 255, 255, 0.1) !important;

  i {
    font-size: 12px !important;
  }

  span {
    font-size: 12px !important;
    white-space: nowrap !important;
  }

  &:hover {
    background: rgba(164, 244, 186, 0.2) !important;
    border-color: rgba(164, 244, 186, 0.5) !important;
    color: rgba(164, 244, 186, 1) !important;
    transform: translateY(-1px) !important;
    box-shadow:
      0 4px 12px rgba(0, 0, 0, 0.15),
      inset 0 1px 0 rgba(255, 255, 255, 0.2),
      0 0 10px rgba(164, 244, 186, 0.3) !important;
  }

  &.replay-btn {
    background: rgba(0, 234, 255, 0.1) !important;
    border-color: rgba(0, 234, 255, 0.3) !important;

    &:hover {
      background: rgba(0, 234, 255, 0.2) !important;
      border-color: rgba(0, 234, 255, 0.5) !important;
      color: rgba(0, 234, 255, 1) !important;
      box-shadow:
        0 4px 12px rgba(0, 0, 0, 0.15),
        inset 0 1px 0 rgba(255, 255, 255, 0.2),
        0 0 10px rgba(0, 234, 255, 0.3) !important;
    }
  }
}



/* 响应式设计 */
@media (max-width: 1200px) {
  .header-content {
    flex-direction: column;
    gap: 20px;
    text-align: center;
  }

  .stats-section {
    justify-content: center;
  }
}
</style>
